<?php

namespace addons\shopro\console;

use addons\shopro\service\commission\Agent;
use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\Refund;
use app\common\model\stat\OrderStat;
use think\Db;
use think\exception\HttpResponseException;
use Workerman\Timer;
use think\console\Input;
use think\console\Output;

class ShoproOrderStat extends Command
{

    protected $input = null;
    protected $output = null;

    /**
     * 帮助命令配置
     */
    protected function configure()
    {
        $this->setName('shopro:order_stat')
            ->setDescription('订单每日统计');
    }


    /**
     * 执行帮助命令
     */
    protected function execute(Input $input, Output $output)
    {
        // 获取昨日的起始和结束时间戳
        $yesterday = getYesterdayDate('int');

        // 计算昨日的总销售额（只统计已支付订单）
        $yesterdayPayFee = Order::where('status', 'paid')
            ->whereBetween('paid_time', [$yesterday['start'], $yesterday['end']])
            ->sum('pay_fee');
        $order_count = Order::where('status', 'paid')
            ->whereBetween('paid_time', [$yesterday['start'], $yesterday['end']])
            ->count();

        $refund_order_count = Refund::whereBetween('createtime', [
            $yesterday['start'], $yesterday['end']
        ])->count();
        $refund_order_money = Refund::whereBetween('createtime', [
            $yesterday['start'], $yesterday['end']
        ])->sum('refund_fee');

        $data = [
            'date' => date('Ymd', $yesterday['start']),
            'order_count' => $order_count,
            'refund_order_cout' => $refund_order_count,
            'refund_order_money' => $refund_order_money,
            'pay_money' => $yesterdayPayFee,
            'real_pay_money' => $yesterdayPayFee - $refund_order_money,
        ];
        OrderStat::where('date', date('Ymd', $yesterday['start']))
            ->delete();
        OrderStat::create($data);

    }

}
